<template>
  <el-upload
    v-model:file-list="options.fileList"
    :class="['avatar-uploader', showUploadBtn ? '' : 'diableCard']"
    :on-preview="handlePictureCardPreview"
    list-type="picture-card"
    :action="props.action"
    :multiple="limit === 1 ? false : true"
    :data="{ category: 1 }"
    :before-upload="methods.handleBeforeUpload"
    :on-remove="handleRemove"
    :on-success="methods.handleSeccess"
    :on-error="methods.handlError"
    :before-remove="methods.beforeRemove"
    :on-change="handleOnChange"
  >
    <el-icon class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>
  <div v-if="state.dialogVisible" class="show_full_image" @click="hideDialog">
    <div class="show_full_image_mask"></div>
    <el-icon class="show_full_image_close" @click="hideDialog">
      <CircleClose />
    </el-icon>
    <div class="show_full_image_cont">
      <img :src="state.dialogImageUrl" alt="Preview Image" />
    </div>
  </div>
</template>

<script setup name="ImageUpload">
import { computed, reactive, watchEffect } from 'vue';
import { setup as fileUpdataSetup } from './fileUpload';
import { Plus,CircleClose } from '@element-plus/icons';

const props = defineProps({
  limit: {
    type: Number,
    default: 12,
  },
  fileList: Array,
  action: {
    type: String,
    default: 'http://114.250.31.154:8087/api-osms-sys/attach/upload',
  },
});

const state = reactive({
  dialogImageUrl: '',
  dialogVisible: false, //弹出框展示
});

const { options, methods } = fileUpdataSetup();

// limit==1时，控制上传按钮的显示和隐藏
const showUploadBtn = computed(() => {
  if (props.limit === 1) {
    if (options.fileList.length >= 1) return false;
    else return true;
  } else {
    return true;
  }
});
const handlePictureCardPreview = (uploadFile) => {
  state.dialogImageUrl = uploadFile.url;
  state.dialogVisible = true;
};
watchEffect(() => {
  if (props.fileList) {
    options.fileList = props.fileList;
  }
});
const emit = defineEmits(['onChange']);
const handleRemove = (file, fileList) => {
  options.fileList = reactive(fileList);
  handleOnChange();
};
const handleOnChange = () => {
  emit('onChange', options.fileList);
};
// 关闭弹出框
const hideDialog = () => {
  state.dialogVisible = false;
};
</script>
<script>
export default {
  name: 'imageUpdata',
};
</script>
<style lang="scss">
@import './index.scss';

.avatar-uploader.diableCard .el-upload--picture-card {
  display: none;
}
</style>
